package com.china08.yxyapi.api.manage.tec.teaching.zujuan.previewpaper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.es.ElasticYxyYxyQuesResource;
import com.china08.yxyapi.entity.mg.res.AllTemplate;
import com.china08.yxyapi.entity.mg.res.AllTemplate.Analysis;
import com.china08.yxyapi.entity.mg.res.AllTemplate.Answer;
import com.china08.yxyapi.entity.mg.res.AllTemplate.Branch;
import com.china08.yxyapi.entity.mg.res.AllTemplate.Sub;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.service.manage.tec.teaching.homework.ElasticQuesService;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

import io.swagger.annotations.ApiOperation;

/**
 * 试卷预览
 * 
 * 
 */
@RestController
@CrossOrigin
public class ZujuanPaperPreviewController extends YxyApiBaseController {

    @Autowired
    private ElasticQuesService elasticQuesService;

    @ApiOperation(value = "试卷预览")
    @RequestMapping(value = "/api_yw/manage/tec/teaching/zujuan/paper/preview", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel)
            throws JsonParseException, JsonMappingException, IOException {

        List<QuestionModel> queslist = reqModel.queslist;
        // 所有的题id
        List<String> quesIdList = queslist.stream().map(x -> x.quesId).collect(Collectors.toList());
        List<ElasticYxyYxyQuesResource> esQuesList = elasticQuesService.findByQuesIdIn(quesIdList);

        Map<String, Integer> collect = new HashMap<String, Integer>();
        if (CollectionUtils.isNotEmpty(queslist)) {
            for (QuestionModel quesModel : queslist) {
                collect.put(quesModel.quesId, quesModel.point);
            }
        }

        // 返回响应题
        List<QuestionRespModel> list1 = new ArrayList<QuestionRespModel>();
        List<QuestionRespModel> list2 = new ArrayList<QuestionRespModel>();
        List<QuestionRespModel> list3 = new ArrayList<QuestionRespModel>();
        List<QuestionRespModel> list4 = new ArrayList<QuestionRespModel>();
        QuestionRespModel model = null;
        // 1单选 2填空 8多选 其他解答
        for (ElasticYxyYxyQuesResource es : esQuesList) {
            String quesType = es.getQuestionType();
            if (StringUtils.equals("1", quesType)) {
                model = new QuestionRespModel();
                model.quesId = es.getId();
                model.quesBody = convertDomainAllTemplate((AllTemplate) es.getQuesBody());
                model.point = collect.get(model.quesId);
                list1.add(model);
            } else if (StringUtils.equals("2", quesType)) {
                model = new QuestionRespModel();
                model.quesId = es.getId();
                model.quesBody = convertDomainAllTemplate((AllTemplate) es.getQuesBody());
                model.point = collect.get(model.quesId);
                list3.add(model);
            } else if (StringUtils.equals("8", quesType)) {
                model = new QuestionRespModel();
                model.quesId = es.getId();
                model.quesBody = convertDomainAllTemplate((AllTemplate) es.getQuesBody());
                model.point = collect.get(model.quesId);
                list2.add(model);
            } else {
                model = new QuestionRespModel();
                model.quesId = es.getId();
                model.quesBody = convertDomainAllTemplate((AllTemplate) es.getQuesBody());
                model.point = collect.get(model.quesId);
                list4.add(model);
            }
        }
        RespModel respModel = new RespModel();
        respModel.danxuanList = list1;
        respModel.duoxuanList = list2;
        respModel.tiankongList = list3;
        respModel.jiedaList = list4;
        return respModel;
    }

    /**
     * 处理试题里的跨域图片
     */
    private AllTemplate convertDomainAllTemplate(AllTemplate allTemplate) {
        Pattern p = Pattern.compile("http:\"?(.*?)(\"|>|\\s+)");
        Sub sub = allTemplate.getSub();
        // 题干
        String body = sub.getStem().getBody();
        Document parse = Jsoup.parse(body);
        Elements select = parse.getElementsByAttributeValueContaining("style", "background");
        for (Element element : select) {
            // 进行替换
            String string = element.attr("style");
            Matcher matcher = p.matcher(string);
            if (matcher.find()) {
                String replaceAll = matcher.replaceAll("/api_yw/comm/proxy?url=" + matcher.group());
                element.attr("style", replaceAll);
            }
        }
        // 重新赋值
        sub.getStem().setBody(parse.toString());
        // 选项
        List<Branch> branch = sub.getBranch();
        for (Branch branch2 : branch) {
            String body2 = branch2.getBody();
            Document pDocument = Jsoup.parse(body2);
            Elements elementsByAttributeValueContaining = pDocument.getElementsByAttributeValueContaining("style",
                    "background");
            for (Element element : elementsByAttributeValueContaining) {
                String string = element.attr("style");
                Matcher matcher = p.matcher(string);
                if (matcher.find()) {
                    String replaceAll = matcher.replaceAll("/api_yw/comm/proxy?url=" + matcher.group());
                    element.attr("style", replaceAll);
                }
            }
            // 重新赋值
            branch2.setBody(pDocument.toString());
        }
        // 重新赋值
        sub.setBranch(branch);
        // 答案
        List<Answer> answer = sub.getAnswer();
        for (Answer answer2 : answer) {
            String body2 = answer2.getBody();
            Document parse2 = Jsoup.parse(body2);
            Elements elementsByAttributeValueContaining = parse2.getElementsByAttributeValueContaining("style",
                    "background");
            for (Element element : elementsByAttributeValueContaining) {
                // 进行替换
                String string = element.attr("style");
                Matcher matcher = p.matcher(string);
                if (matcher.find()) {
                    String replaceAll = matcher.replaceAll("/api_yw/comm/proxy?url=" + matcher.group());
                    element.attr("style", replaceAll);
                }
            }
            // 重新赋值
            answer2.setBody(parse2.toString());
        }
        // 重新赋值
        sub.setAnswer(answer);
        // 解析
        Analysis analysis = sub.getAnalysis();
        String body2 = analysis.getBody();
        Document parse2 = Jsoup.parse(body2);
        Elements elementsByAttributeValueContaining = parse2.getElementsByAttributeValueContaining("style",
                "background");
        for (Element element : elementsByAttributeValueContaining) {
            // 进行替换
            String string = element.attr("style");
            Matcher matcher = p.matcher(string);
            if (matcher.find()) {
                String replaceAll = matcher.replaceAll("/api_yw/comm/proxy?url=" + matcher.group());
                element.attr("style", replaceAll);
            }
        }
        analysis.setBody(parse2.toString());
        sub.setAnalysis(analysis);
        return allTemplate;
    }

    protected static class ReqModel extends YxyApiReqModel {
        // 试题请求模型
        public List<QuestionModel> queslist;
    }

    /**
     * 试题请求模型
     * 
     */
    protected static class QuestionModel {
        // 试题id
        public String quesId;
        // 题型
        public String quesType;
        // 试题涉及的知识点
        public List<Integer> know;
        // 试题的分数
        public Integer point;

        public String getQuesId() {
            return quesId;
        }

        public void setQuesId(String quesId) {
            this.quesId = quesId;
        }

        public String getQuesType() {
            return quesType;
        }

        public void setQuesType(String quesType) {
            this.quesType = quesType;
        }

        public List<Integer> getKnow() {
            return know;
        }

        public void setKnow(List<Integer> know) {
            this.know = know;
        }

        public Integer getPoint() {
            return point;
        }

        public void setPoint(Integer point) {
            this.point = point;
        }
    }

    protected static class RespModel extends YxyApiRespModel {
        // 单选
        public List<QuestionRespModel> danxuanList;
        // 多选
        public List<QuestionRespModel> duoxuanList;
        // 填空
        public List<QuestionRespModel> tiankongList;
        // 解答
        public List<QuestionRespModel> jiedaList;
    }

    protected static class QuestionRespModel {
        // 题id
        public String quesId;
        // 题干
        public AllTemplate quesBody;
        // 试题的分数
        public Integer point;
    }

}
